package cn.coufran.springboot.starter.http.content;

import cn.coufran.springboot.starter.http.MultipartBody;
import cn.coufran.springboot.starter.http.exception.HttpException;

import java.io.*;

/**
 * @author Coufran
 * @version 2.0.0
 * @since 2.0.0
 */
public class FileContent extends HttpBodyContent<File> implements HttpRequestBodyContent {
    private File content;

    public FileContent(String name, File content) {
        super(name);
        this.content = content;
    }

    public FileContent(File content) {
        this.content = content;
    }

    @Override
    public File content() {
        return this.content;
    }

    @Override
    public void accept(MultipartBody.Builder multipartBodyBuilder) {
        try {
            multipartBodyBuilder.addPart(name(), content());
        } catch (IOException e) {
            throw new HttpException(e);
        }
    }

    @Override
    public InputStream getInputStream() {
        try {
            return new BufferedInputStream(new FileInputStream(content()));
        } catch (FileNotFoundException e) {
            throw new HttpException(e);
        }
    }

    @Override
    public String toString() {
        return "FileContent{" +
                "content=" + content +
                "} " + super.toString();
    }
}
